// src/stores/mqttStore.ts
import { defineStore } from 'pinia'
import { ref, watch } from 'vue'
import { createMqttClient } from '@/utils/mqttClient'
import type { MqttClient } from 'mqtt'

export const useMqttStore = defineStore('mqtt', () => {
  const client = ref<MqttClient | null>(null)
  const isConnected = ref(false)
  const messageHandlers = new Map<string, (payload: string) => void>()

  const connect = () => {
    if (client.value) return
    client.value = createMqttClient()

    client.value.on('connect', () => {
      // console.log('MQTT Connected')
      isConnected.value = true
    })

    client.value.on('reconnect', () => {
      // console.log('MQTT Reconnecting...')
    })

    client.value.on('error', (err) => {
      console.error('MQTT Error:', err)
    })

    client.value.on('message', (topic, payload) => {
      // console.log('MQTT Message:', topic, payload.toString())
      const handler = messageHandlers.get(topic)
      if (handler) handler(payload.toString())
    })
  }

  const subscribe = (topic: string, handler: (payload: string) => void) => {
    if (!client.value) return
    messageHandlers.set(topic, handler)
    client.value.subscribe(topic)
  }

  const unsubscribe = (topic: string) => {
    if (!client.value) return
    messageHandlers.delete(topic)
    client.value.unsubscribe(topic)
  }

  return {
    client,
    isConnected,
    connect,
    subscribe,
    unsubscribe
  }
})
